const fs=require("fs");
async function readFileAsFrames(filePath, sampleRate=16000, channelCount=2, ptime=20){
    //s16le
    let bytesPerFrame = 16000/(1000/ptime) * 2 * 2
    let totalResult = [];

    return new Promise((resolve,reject) => {
        fs.readFile(filePath, function read(err, data) {
            if (err) {
                reject(err);
            }
            for(let i=0;i<data.byteLength;i=i+bytesPerFrame){
                totalResult.push(data.slice(i, i+bytesPerFrame));
            }
            console.log('read over', totalResult.length);
            resolve(totalResult);
        });
    });
}

async function writeData(dataArray, fileName='result.pcm'){
    let totalBuffer = Buffer.allocUnsafe(0);
    for(let i=0;i<dataArray.length;i++){
        totalBuffer = Buffer.concat([totalBuffer, dataArray[i]]);
    }

    fs.writeFile(fileName, totalBuffer,  "binary",function(err) {
        if(err) {
            console.log(err);
        } else {
            console.log("The file was saved!");
        }
    });
    console.log('start to write to file', dataArray.length);
}

module.exports = {readFileAsFrames, writeData}
